﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using GiveAQuiz.Data;
using GiveAQuiz.Web.Authentication;
using GiveAQuiz.Web.Helpers;
using GiveAQuiz.Web.Membership;
using GiveAQuiz.Web.Messenger;
using GiveAQuiz.Web.Models;

namespace GiveAQuizSite.Controllers
{
    [HandleError]
    public class RegistrationController : AuthenticationController
    {
      /// <summary>
      /// Creates an instance of the RegistrationController.
      /// </summary>
      /// <param name="repository">The QuizRepository.</param>
      /// <param name="formsAuth">The Forms Authentication module.</param>
      /// <param name="membershipService">The Membership Service.</param>
      /// <param name="acctMessenger">The Account Messenger service.</param>
      public RegistrationController(IQuizRepository repository,
        IFormsAuthentication formsAuth,
        IMembershipService membershipService,
        IAccountMessenger acctMessenger)
        : base(repository, formsAuth, membershipService, acctMessenger)
      {
      }

      /// <summary>
      /// ~/Registration
      /// </summary>
      /// <returns>~/Views/Registration/Index.aspx</returns>
      public ActionResult Index()
      {
        ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        return View();
      }

      /// <summary>
      /// ~/Registration/Register
      /// </summary>
      /// <param name="model">The form parameters bound to a 
      /// RegistrationViewModel object.</param>
      /// <returns>~/Views/Registration/RegistrationVerification.aspx</returns>
      [AcceptVerbs(HttpVerbs.Post)]
      public ActionResult Register(RegistrationViewModel model)
      {
        ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

        if (!ModelState.IsValid)
        {
          return View("Index", model);
        }

        // Attempt to register the user
        MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

        if (createStatus == MembershipCreateStatus.Success)
        {
          MembershipUser user = MembershipService.GetUser(model.UserName);

          Guid userId = (Guid)user.ProviderUserKey;

          // we also track First and Last Name
          QuizUser quizUser = 
            new QuizUser {Id = userId, FirstName = model.FirstName, LastName = model.LastName};
          Repository.SaveUser(quizUser);

          // don't approve the user until the e-mail address is confirmed
          user.IsApproved = false;
          MembershipService.UpdateUser(user);

          AccountMessenger.SendRegistrationVerificationMessage(user);

          return View("Verify");
        }
        else
        {
          ModelState.AddModelError("_FORM", createStatus.PrintErrorMessage());
        }

        // If we got this far, something failed, redisplay form
        return View("Index");
      }

      /// <summary>
      /// ~/Registration/Confirm/user?token=AB12CD34EF56
      /// </summary>
      /// <param name="model">The form parameters bound to a 
      /// ConfirmRegistrationViewModel object.</param>
      /// <returns>~/Views/Registration/Confirm.aspx</returns>
      public ActionResult Confirm(ConfirmRegistrationViewModel model)
      {
        ViewData["UserName"] = model.UserName;

        // call ConfirmRegistrationValidation
        if (!ModelState.IsValid)
        {
          ViewData["IsError"] = true;
          return View();
        }

        // no errors - set the approval flag to true
        MembershipUser user = MembershipService.GetUser(model.UserName);
        
        user.IsApproved = true;
        MembershipService.UpdateUser(user);

        // go ahead and sign the user in
        FormsAuth.SignIn(user.UserName, false /* createPersistentCookie */);
        return View();
      }

      /// <summary>
      /// ~/Registration/Resend/user
      /// </summary>
      /// <param name="id">The username.</param>
      /// <returns>~/Views/Registration/Verify.aspx</returns>
      public ActionResult Resend(string id)
      {
        MembershipUser user = MembershipService.GetUser(id);
        AccountMessenger.SendRegistrationVerificationMessage(user);
        return View("Verify");
      }
    }
}
